package com.nsgf.library.ui.mine;

import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.media3.common.C;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_state.BR;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.ToastUtils;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivitySignVideoBinding;

public class VideoActivity extends BaseActivity {


    private String TAG = "VideoActivity";
    private ActivitySignVideoBinding mBinding;
    private AccountRequester mAccountRequester;

    private SignVideoStates mStates;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(SignVideoStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    private ExoPlayer player;

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_sign_video, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mStates.titleBar.set("签到领积分");
        mBinding = (ActivitySignVideoBinding) getBinding();


        // 初始化ExoPlayer，添加更多配置
        ExoPlayer.Builder playerBuilder = new ExoPlayer.Builder(this);
        // 设置媒体源工厂，添加更多格式支持
        DefaultMediaSourceFactory mediaSourceFactory = new DefaultMediaSourceFactory(this)
                .setLiveMaxOffsetMs(5000)
                .setLiveTargetOffsetMs(1000);
        playerBuilder.setMediaSourceFactory(mediaSourceFactory);

        player = playerBuilder.build();
        mBinding.playerView.setPlayer(player);

        // 设置播放器参数
        player.setPlayWhenReady(true);
        player.setVideoScalingMode(C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);

        // 设置播放器监听器
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                String stateString;
                switch (state) {
                    case Player.STATE_IDLE:
                        stateString = "STATE_IDLE";
                        break;
                    case Player.STATE_BUFFERING:
                        stateString = "STATE_BUFFERING";
                        break;
                    case Player.STATE_READY:
                        stateString = "STATE_READY";
                        break;
                    case Player.STATE_ENDED:
                        stateString = "STATE_ENDED";
                        break;
                    default:
                        stateString = "UNKNOWN_STATE";
                }
                Log.d(TAG, "播放状态改变: " + stateString);
            }

            @Override
            public void onPlayerError(PlaybackException error) {
                String errorMessage = "播放错误: " + error.getMessage();
                Log.e(TAG, errorMessage, error);
                Toast.makeText(VideoActivity.this, errorMessage, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                Log.d(TAG, "播放状态: " + (isPlaying ? "正在播放" : "已暂停"));
            }
        });
        mAccountRequester.getSignVideo();
        mAccountRequester.getLibraryInfo().observe(this, new Observer<ResponseStatus<LibraryInfo>>() {
            @Override
            public void onChanged(ResponseStatus<LibraryInfo> objectResponseStatus) {
                if (objectResponseStatus.getResponseCode() == 0) {
                    playVideo(objectResponseStatus.getData().getVideo());
                    startCountDownTimer(objectResponseStatus.getData().getTime());
                }
            }
        });
        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                }
            }
        });
    }

    public static class SignVideoStates extends StateHolder {

    }


    private void playVideo(String url) {
        try {
            Log.d(TAG, "开始播放视频: " + url);

            // 创建媒体项，添加更多配置
            MediaItem mediaItem = new MediaItem.Builder()
                    .setUri(Uri.parse(url))
                    .setMimeType("video/mp4")  // 明确指定MIME类型
                    .build();

            // 停止当前播放
            player.stop();
            player.clearMediaItems();

            // 设置新的媒体项并准备播放
            player.setMediaItem(mediaItem);
            player.prepare();
            player.play();

            Log.d(TAG, "视频加载完成，开始播放");
        } catch (Exception e) {
            String errorMessage = "播放失败: " + e.getMessage();
            Log.e(TAG, errorMessage, e);
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.setPlayWhenReady(true);
        }
        if (null != timer) {
            timer.cancel();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.setPlayWhenReady(false);
        }
        if (null != timer) {
            timer.cancel();
        }
    }

    CountDownTimer timer;

    private void startCountDownTimer(int time) {

        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvSignVideoTime.setText(millisUntilFinished / 1000 + "秒");

            }

            @Override
            public void onFinish() {
                mBinding.tvSignVideoTime.setText("0秒");
                mAccountRequester.createSignIn();
            }
        };
        timer.start();
    }
}
